package com.example.gpstracking.service;

import java.util.Calendar;

import com.example.gpstracking.database.MySQLiteManager;
import com.example.gpstracking.database.MySqliteHelper;
import com.example.gpstracking.database.SharedPreferenceSaver;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSService extends Service implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener{

	//
	private final static String TAG = "GPSERVICE";
	private boolean mCurrentlyProcessingLocation = false;
	private LocationRequest mLocationRequest;
	private LocationClient mLocationClient;
	private MySQLiteManager mMySQLiteManager;
	//
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "mCurrentlyProcessingLocation: "+ mCurrentlyProcessingLocation);
		if(!mCurrentlyProcessingLocation)
		{
			Log.d(TAG, "mCurrentlyProcessingLocation: "+ mCurrentlyProcessingLocation);
			mCurrentlyProcessingLocation = true;
			startTracking();
		}
		return START_STICKY;
	}
	public void startTracking()
	{
		if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS)
		{
			
			Log.d(TAG, "startTracking");
			mLocationClient = new LocationClient(this, this, this);
			if(!mLocationClient.isConnected() || !mLocationClient.isConnecting())
			{
				mLocationClient.connect();
			}
		}
		else
			Log.d(TAG, "unable to connect to google play services.");
		
	}
	public void stopLocationUpdates()
	{
		if( ( mLocationClient != null ) || mLocationClient.isConnected())
		{
			
			mLocationClient.removeLocationUpdates(this);
			mLocationClient.disconnect();
		}
	}
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if (location != null) {
            
			Log.d(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
            //
			//
            // don't need log accuracy here .
                stopLocationUpdates();
                // 
                SharedPreferenceSaver preferenceSaver = new SharedPreferenceSaver(this);
                if(isFistTimeTrack(preferenceSaver))
                {
                	preferenceSaver.savePreferences((float)location.getLatitude(), (float)(location.getLongitude()) );
                	saveSQLite(location);
                }
                else
                {
                	String currentLocationS = preferenceSaver.getPreferences();                	
                	String[] temp = currentLocationS.split(",");
                	double lat = Double.valueOf(temp[0].trim()), lng = Double.valueOf(temp[1].trim());
                	Location currentLocation = new Location("");
                	currentLocation.setLatitude(lat);
                	currentLocation.setLongitude(lng);
                	float distance = location.distanceTo(currentLocation);
                	Log.d(TAG, distance + "m");
                	preferenceSaver.savePreferences(location.getLatitude(), location.getLongitude());
                	if(distance > 5.0f)
                	{                		
                		Log.d(TAG, "savelocation");
                		saveSQLite(location);
                	}
                }           
                
            }        
	}
	public void saveSQLite(Location location)
	{
			
		//		
		Calendar calendar = Calendar.getInstance();
		mMySQLiteManager = new MySQLiteManager(this.getApplicationContext());
		long time  = calendar.getTimeInMillis();
		double lat  = location.getLatitude(), lng  = location.getLongitude();
		ContentValues contentValues = new ContentValues();
		//
		contentValues.put(MySqliteHelper.TABLE_TIME, time);
		contentValues.put(MySqliteHelper.TABLE_LAT, lat);
		contentValues.put(MySqliteHelper.TABLE_LONG, lng);
		//save
		mMySQLiteManager.InsertData(contentValues);
		//stop service
		stopSelf();
	}
	
	@Override
	public void onConnected(Bundle connectionHint) {
		// TODO Auto-generated method stub
		mLocationRequest = LocationRequest.create();
		//
		mLocationRequest.setInterval(2000);// 2s
		mLocationRequest.setFastestInterval(1000);
		mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);// set priorrity
		//
		mLocationClient.requestLocationUpdates(mLocationRequest, this);
	}
	public boolean isFistTimeTrack(SharedPreferenceSaver preferenceSaver)
	{
		String currentRes = preferenceSaver.getPreferences();
		if(currentRes != null && !currentRes.equals(""))
		{
			return false;
		}
		return true;
	}
	

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onConnectionFailed");
	}
	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		Log.d(TAG, "onConnectionFailed");
		//mLocationClient = null;
	}
	

}
